package com.free.picture.ecognition.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.free.common.core.web.domain.R;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController()
@RequestMapping("/baidu")
@Slf4j
public class BaiduAudioController {
    //设置APPID/AK/SK
    public static final String API_KEY = "8hT1F5NHD2SXw1iwaH9gz6kN";
    public static final String SECRET_KEY = "OhIjZ2do9mAWQRKENOdTnHgf72lMC0cl";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @PostMapping("create")
    private static R<String> create(@org.springframework.web.bind.annotation.RequestBody String fileUrl) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        String[] split = fileUrl.split(".");

        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "{\"speech_url\":\"" + "fileUr" + "l\",\"format\":\"" + split[split.length - 1] + "\",\"pid\":80001,\"rate\":16000}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/aasr/v1/create?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String string = response.body().string();
        log.info("提交的任务:{}", string);
        return R.ok(JSONUtil.parseObj(string).getStr("task_id"));
    }

    @PostMapping("getResult")
    public R<String> getContent(@org.springframework.web.bind.annotation.RequestBody String orderId) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "{\"task_ids\":[\"" + orderId + "\"]}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/aasr/v1/query?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        ResponseBody responseBody = response.body();
        String string = responseBody.string();
        StringBuilder result = new StringBuilder();


        cn.hutool.json.JSONObject resultJson = JSONUtil.parseObj(JSONUtil.parseObj(string).getJSONArray("tasks_info").get(0));
        if ("Success".equals(resultJson.getStr("task_status"))){
            JSONUtil.parseObj(string).getJSONArray("tasks_info").forEach(e -> {
                cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(e);
                JSONArray jsonArray = jsonObject.getJSONObject("task_result").getJSONArray("detailed_result");
                jsonArray.forEach(str -> {
                    result.append(JSONUtil.parseObj(str).getJSONArray("res").get(0));
                });
            });
            return R.ok(result.toString());
        }
        return R.ok(null);
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        okhttp3.RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }


}
